﻿layui.use(['form', 'layer', 'table', 'element'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        element = layui.element,
        table = layui.table;

    var xxx = getUrlParam('culture');

    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]); return null; //返回参数值
    }

    var FileName = '文件名';
    var FileType = '文件类型';
    var FilePath = '文件路径';
    var Operation = '操作';
    var MsgConfirmBatchDelete = '确定删除选中的文件吗?';
    var MsgConfirmDelete = '确定删除此文件?';
    var MsgChooseNeedDelete = '请选择需要删除的文件';
    var SystemPrompt = '系统提示';
    var iframeTit = '文件上传';

    if (xxx == 'en') {
        FileName = 'File Name';
        FileType = 'File Type';
        FilePath = 'Path';
        Operation = 'Operation';
        MsgConfirmBatchDelete = 'Make sure to delete the selected files?';
        MsgConfirmDelete = 'Are you sure to delete this file?';
        MsgChooseNeedDelete = 'Please select the file you want to delete';
        SystemPrompt = 'System Prompt';
        iframeTit = 'File Upload';
    }

    if (xxx == 'vi') {
        FileName = 'Tên tập tin';
        FileType = 'Kiểu tập tin';
        FilePath = 'Đường dẫn';
        Operation = 'Nút hoạt động';
        MsgConfirmBatchDelete = 'Bạn có chắc là xóa các tùy chọn đã chọn không?';
        MsgConfirmDelete = 'Bạn có chắc chắn để loại bỏ?';
        MsgChooseNeedDelete = 'Hãy chọn cái cần xoá';
        SystemPrompt = 'Hệ thống gợi ý';
        iframeTit = 'Tải lên tập tin';
    }

    //用户列表
    var tableIns = table.render({
        elem: '#fileList',
        url: '/Assets/LoadData/',
        cellMinWidth: 50,
        page: true,
        height: "full-125",
        limits: [10, 15, 20, 25],
        limit: 10,
        id: "fileListTable",
        cols: [[
            { type: "checkbox", fixed: "left", width: 50 },
            { field: 'Name', title: FileName, minWidth: 100, align: "center" },
            { field: 'Type', title: FileType, minWidth: 50, align: "center" },
            { field: 'Path', title: FilePath, minWidth: 300, align: "center" },
            { title: Operation, minWidth: 90, templet: '#fileListBar', fixed: "right", align: "center" }
        ]]
    });

    //批量删除
    $(".delAll_btn").click(function () {
        var checkStatus = table.checkStatus('fileListTable'),
            data = checkStatus.data,
            fileId = [];
        if (data.length > 0) {
            for (var i in data) {
                fileId.push(data[i].Id);
            }
            layer.confirm(MsgConfirmBatchDelete, {
                btn: ['Yes', 'No'], //可以无限个按钮
                btn1: function (index, layero) {
                    del(fileId);
                    //按钮【按钮三】的回调
                }, title: SystemPrompt
            });
        } else {
            layer.msg(MsgChooseNeedDelete);
        }
    });

    //列表操作
    table.on('tool(fileList)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;

        if (layEvent === 'del') { //删除
            fileId = [];
            fileId.push(data.Id);
            layer.confirm(MsgConfirmDelete, {
                btn: ['Yes', 'No'], //可以无限个按钮
                btn1: function (index, layero) {
                    del(fileId);
                }, title: SystemPrompt
            });
        }
    });

    function del(fileId) {
        $.ajax({
            type: 'POST',
            url: '/Assets/Delete/',
            data: { fileId: fileId },
            dataType: "json",
            headers: {
                "X-CSRF-TOKEN-Gerald": $("input[name='AntiforgeryKey_Gerald']").val()
            },
            success: function (data) {//res为相应体,function为回调函数
                layer.msg("操作成功", {
                    time: 2000 //20s后自动关闭
                }, function () {
                    tableIns.reload();
                    layer.close(index);
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.alert("失败" + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
            }
        });
    }

    $(".coursefile").show();
    $(".courseexam").hide();

    form.on("submit(submitUpload)", function (data) {
        var files = $("#CourseFile")[0].files;
        //var coverImageFile = $("#CourseCoverImage")[0].files[0];
        $.each(files, function (i, file) {
            AjaxFile(file, 0);
        });
    });

    form.on("radio(CourseTypeFilter)", function (data) {
        if (data.value == 0) {
            $(".coursefile").show();
            $(".courseexam").hide();
        } else if (data.value == 1) {
            $(".coursefile").hide();
            $(".courseexam").show();
        }
    });

    function AjaxFile(file, i) {
        var name = file.name, size = file.size, shardSize = 2 * 1024 * 1024, shardCount = Math.ceil(size / shardSize);
        if (shardCount <= 0) {
            return;
        }

        //每一片的起始与结束位置
        var start = i * shardSize, end = Math.min(size, start + shardSize);

        var form = new FormData();
        //form.append("TaskId", $(".TaskId").val());
        //form.append("TaskName", $(".TaskId option:selected").text());
        //form.append("CategoryName", $(".CategoryName").val());
        //form.append("CategoryDescription", $(".CategoryDescription").val());
        //form.append("CourseName", $(".CourseName").val());
        //form.append("CourseDescription", $(".CourseDescription").val());
        form.append("FileData", file.slice(start, end));
        form.append("FileName", name);
        form.append("FileTotal", shardCount);
        form.append("FileIndex", i + 1);
        $.ajax({
            type: "POST",
            url: "/Assets/Add/",
            data: form,
            dataType: "json",
            async: false,
            processData: false,
            contentType: false,
            headers: {
                "X-CSRF-TOKEN-Gerald": $("input[name='AntiforgeryKey_Gerald']").val()
            },
            beforeSend: function () {
                //layer.load();
            },
            success: function (result) {
                var alertIndex;
                if (result != null && i < shardCount - 1) {
                    i++;
                    AjaxFile(file, i);
                } else {
                    alertIndex = layer.alert(result.ResultMsg, { icon: 1 });
                }
                //loading = layer.load(0, { shade: true, time: 2 * 1000 });
            },
            end: function () {
                //layer.closeAll('loading');
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(JSON.stringify(data));
                console.log(JSON.stringify(data));
                layer.alert('操作失败！！！' + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
            }
        })
    }

    $(".upload_btn").click(function () {
        layui.layer.open({
            title: iframeTit,
            type: 2,
            anim: 1,
            area: ['800px', '80%'],
            content: "/Assets/AssetsUpload?culture=" + xxx,
            success: function (layero, index) {
                //alert('success');
            }
        });
    });
});